// pages/orderedia/orderedia.js
//读取下单数据，订单支付  提交订单 微信签名
import { getCreate, setPlayComPlet, setUpSubmit, getPayShow} from '../../config/https'

import Toast from '../../miniprogram_npm/_vant-weapp@0.5.7@vant-weapp/toast/toast'; 

var time = [
  '09:00-10:00',
  '10:00-11:00',
  '11:00-12:00',
  '12:00-13:00',
  '13:00-14:00',
  '14:00-15:00',
  '15:00-16:00',
  '16:00-17:00',
  '17:00-18:00',
  '18:00-19:00',
  '19:00-20:00',
]
var util = require("../../utils/util.js")
const times = util.formatDate(new Date());
//读取近七天的日期
let date = util.getDates(2, times);
//获取时间
var myDate = new Date();
const hours = myDate.getHours() + 2;
const timeArr = []
var citys = new Object;
if(hours >= 20){
  date.shift();
  var citysList = '(' + date[0].week + ')' + date[0].time;
  citys[citysList] = [
    '09:00-10:00',
    '10:00-11:00',
    '11:00-12:00',
    '12:00-13:00',
    '13:00-14:00',
    '14:00-15:00',
    '15:00-16:00',
    '16:00-17:00',
    '17:00-18:00',
    '18:00-19:00',
    '19:00-20:00',
  ]
}else{
  date.forEach((item, index) => {
    var citysList = '(' + item.week + ')' + item.time;
    if(index==0){
      var arrTime =[]
      time.forEach((item, index) => {
        if (Number(item.substr(0, 2)) >= hours) {
          arrTime.push(time[index])
        }
      })
      citys[citysList] = arrTime
    }else{
      citys[citysList] = [
        '09:00-10:00',
        '10:00-11:00',
        '11:00-12:00',
        '12:00-13:00',
        '13:00-14:00',
        '14:00-15:00',
        '15:00-16:00',
        '16:00-17:00',
        '17:00-18:00',
        '18:00-19:00',
        '19:00-20:00',
      ]
    }
  
  })
}

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    stast: true,             //用于判断是否可以点击支付
    storesIndex:0,
    columns: [
      {
        values: Object.keys(citys),
        className: 'column1'
      },
      {
        values: citys['(' + date[0].week + ')' + date[0].time],
        className: 'column2',
        defaultIndex: 2
      }
    ],
    isDirect:0,                                                            //是否是直销商品1是0不是
    show: false,                                                            //弹出框时间选择

    cartId:'',                                                              //是否是购物车过来的                      
    tiemvalue:'',                                                           //选择自提的时间
    inCall:'',                                                              //电话
    inName:'',                                                              //名字
    remark:'',                                                              //备注
    toprom:'',                                                              //优惠券信息
    dispatcharr:null,                                                       //判断
    addreId:'',                                                             //地址id
    stores:null,                                                            //门店自提信息
    options: null,                                                          //读取上个页面传过来的数据  
    addressData: null,                                                      //地址信息默认地址
    vipType: '',                                                            //vip状态1是0不是
    shopList: null,                                                         //商品数据
    otherData: null,                                                        //商品信息统计
    status: true,                                                           //false地址不存在true存在
    radio: '0',                                                               //1门店自提0商家配送
    resSet:''                                                              //后台是否支持自提或者配送

  },
  openvip(){ //点击开通vip
    wx.reLaunch({
      url: '/pages/tapswitching/tapswitching?active=3',
    })
  },
  onConfirm(event) {
    const { picker, value, index } = event.detail;
    this.setData({
      tiemvalue: value[0] +' '+ value[1]
    }) 
    this.onClose()
  },

  onCancel() {
    Toast('取消');
    this.onClose();
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    picker.setColumnValues(1, citys[value[0]]);
  },
  //弹出框
  onClose(){
    var show = !this.data.show;
    this.setData({show})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    console.log(options)
    var that = this 
    wx.setStorage({ key: 'nearbyID', data: ' ' })
    // if (wx.getStorageSync('tiemvalue') != null){  //时间
    //   that.setData({ tiemvalue: wx.getStorageSync('tiemvalue')})
    // }

    if (wx.getStorageSync('inCall') != null) {  //电话 
      that.setData({ inCall: wx.getStorageSync('inCall') })
    }

    if (wx.getStorageSync('inName') != null) { //名字
      that.setData({ inName: wx.getStorageSync('inName') })
    }
    
    that.setData({
      options,
    })
    if (options.cartId){
      that.setData({
        cartId: options.cartId
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.pageLoading = !1; //限制跳转
    var that =this
    // 读取vip
    wx.getStorage({
      key: 'vipStast',
      success: function (res) {
        that.setData({
          vipType: res.data
        })
      },
    })
    if (app.globalData.storesIndex) {
      this.setData({ storesIndex: app.globalData.storesIndex })
    }
    //读取优惠券
    wx.getStorage({
      key: 'toprom',
      success: function(res) {
        var toprom = JSON.parse(res.data)
        that.setData({toprom})
        console.log(that.data.toprom)
      },
    })
    //读取其他页面过来的id
    var id = JSON.parse(that.data.options.id)
    if (!that.data.options.optionid) {
      var optionid = [''];
      optionid.length = id.length
    } else {
      var optionid = JSON.parse(that.data.options.optionid)
    }
    var total = JSON.parse(that.data.options.total)
    var goods_data = new Object();
    for (let i = 0; i < id.length; i++) {
      goods_data[i] = {
        'id': id[i],
        'optionid': optionid[i],
        'total': total[i]
      }
    }
    
    that.setData({
      goodsList: JSON.stringify(goods_data)
    })
    //读取本地缓存是否存在地址id
    wx.getStorage({
      key: 'addreId',
      success: function(res) {  //如果本地缓存里有id
        var addreId = res.data;
        getCreate({ //读取下单数据
          goods_data: goods_data,
          address_id: addreId, 
          fromcart: that.data.options.typeCar
        }).then(res => {
          console.log('11111111111')
          console.log(res)
          //配送订单为0 不支持配送
          if (res.set.is_delivery == 0) {
            if (res.set.is_selflift == 1) {
              that.setData({ radio: '1' })
            } else {
              that.setData({ radio: '' })
            }
          } else if (res.set.is_delivery == 1) {
            that.setData({ radio: '0' })
          } 


          let stores = JSON.stringify(res.stores)
          wx.setStorage({
            key: 'stores',
            data: stores,
          })
          that.setData({
            addressData: res.address,
            shopList: res.goods_list,
            otherData: res.other_data,
            stores: res.stores,
            resSet: res.set,
            dispatcharr: res.dispatch_array,
            isDirect: res.other_data.is_direct_sale
          })
          
        }).catch(err => {
          Toast(err.message)
          this.pageLoading = !this.pageLoading;
        })
      }, fail() {             //如果本地缓存里没有id

        wx.getStorage({  //判断有没有修改自提订单的地址，有的话缓存了id的，就让他不执行数据重新加载
          key: 'nearbyID',
          success: function (res){
            if (res.data==' '){
              var addreId = ''
              getCreate({
                goods_data: goods_data,
                address_id: addreId,
                fromcart: that.data.options.typeCar
              }).then(res => {
                console.log('2222222222222')
                // console.log(res)
                //配送订单为0 不支持配送
                if (res.set.is_delivery == 0) {
                  if (res.set.is_selflift == 1) {
                    that.setData({ radio: '1' })
                  } else {
                    that.setData({ radio: '' })
                  }
                } else if (res.set.is_delivery == 1) {
                  that.setData({ radio: '0' })
                }


                let stores = JSON.stringify(res.stores)
                wx.setStorage({
                  key: 'stores',
                  data: stores,
                })
                
                that.setData({
                  addressData: res.address,
                  shopList: res.goods_list,
                  otherData: res.other_data,
                  stores: res.stores,
                  dispatcharr: res.dispatch_array,
                  isDirect: res.other_data.is_direct_sale,
                  resSet: res.set
                })
              }).catch(err => {
                Toast(err.message)
                this.pageLoading = !this.pageLoading;
              })
            }
            // console.log(res)
          },
          fail() {  //如果没有id,才让他正常执行
            var addreId = ''
            getCreate({
              goods_data: goods_data,
              address_id: addreId,
              fromcart: that.data.options.typeCar
            }).then(res => {
              console.log('333333333333333333')
              // console.log(res)
              //配送订单为0 不支持配送
              if (res.set.is_delivery == 0) {
                if (res.set.is_selflift == 1) {
                  that.setData({ radio: '1' })
                } else {
                  that.setData({ radio: '' })
                }
              } else if (res.set.is_delivery == 1) {
                that.setData({ radio: '0' })
              }


              let stores = JSON.stringify(res.stores)
              wx.setStorage({
                key: 'stores',
                data: stores,
              })

              that.setData({
                addressData: res.address,
                shopList: res.goods_list,
                otherData: res.other_data,
                stores: res.stores,
                isDirect: res.other_data.is_direct_sale,
                resSet: res.set
              })
            }).catch(err => {
              Toast(err.message)
              this.pageLoading = !this.pageLoading;
            })
          }
        })
      
      }
    })
  },

  // 单选框切换
  onChanges(e) {
    console.log(e)
    this.setData({ radio: e.detail })
  },
  // 监听买家留言输入事件
  onInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  onName(e) {
    this.setData({
      inName: e.detail.value
    })
  },
  onCall(e) {
    this.setData({
      inCall: e.detail.value
    })
  },
  //点击优惠券
  onCponcunt(){
    if (this.data.otherData.couponcount == 0 || !this.data.otherData.couponcount){
      Toast("当前没有优惠券选择!!!")
      this.pageLoading = !this.pageLoading;
      return
    }else{
      var options = this.data.options
      wx.navigateTo({
        url: '/pages/Topromote/Topromote?type=1&id='+options.id+'&optionid='+options.optionid+'&total='+options.total,
      })
    }
  },
  //点击微信支付
  paymenStatus() {
    console.log("hhhh")
    if (!this.pageLoading) {
      this.pageLoading = !0;
      if (!this.data.stast) {
        // Toast("当前有订单正在进行,请稍后再试~~")
        return
      }
      var goodsList = JSON.parse(this.data.goodsList);
      var addressData = this.data.addressData
      var tiemvalue = this.data.tiemvalue
      var radio = this.data.radio     //1自提0商家配送
      var stores = this.data.stores
      var toprom = this.data.toprom;
      var remark = this.data.remark;
      var dispatcharr = this.data.dispatcharr;
      if (!this.data.tiemvalue && radio == 1) {
        Toast("请选择自提时间")
        this.pageLoading = !this.pageLoading;
        return
      }
      if (!addressData.id && radio == 0) {
        Toast("请选择收货地址")
        this.pageLoading = !this.pageLoading;
        return
      }
      if (dispatcharr.city_express_state == 0 && radio == 0) {
        Toast("当前地址不支持配送")
        this.pageLoading = !this.pageLoading;
        return
      }
      if (!this.data.inName && radio == 1) {
        Toast("请输入联系人")
        this.pageLoading = !this.pageLoading;
        return
      }
      let yinwen = /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/
      if (!(yinwen.exec(this.data.inName)) && radio == 1) {
        Toast("请输入正确的联系人")
        this.pageLoading = !this.pageLoading;
        return
      }
      if (!this.data.inCall && radio == 1) {
        Toast("请输入联系人电话")
        this.pageLoading = !this.pageLoading;
        return
      }
      let telStr = /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/
      if (!(telStr.exec(this.data.inCall)) && radio == 1) {
        Toast("请输入正确的联系人电话")
        this.pageLoading = !this.pageLoading;
        return
      }
      var carriers = new Object;
      carriers['carrier_realname'] = this.data.inName
      carriers['carrier_mobile'] = this.data.inCall
      carriers['carrier_date'] = this.data.tiemvalue
      //提交订单
      console.log(Boolean(wx.getStorageSync('userid'))+"分享人的二维码")
      var that = this
      setUpSubmit({
        reservation_time: radio == 1 ? tiemvalue : '',
        addressid: radio == 0 ? addressData.id : '',
        goods_data: goodsList,
        carrierid: radio == 1 ? stores[that.data.storesIndex].id : '',
        couponid: toprom != '' ? Number(toprom.id) : '',
        remark: remark,
        dispatchtype: radio,
        carriers: carriers,
        fromcart: that.data.options.typeCar,
        share_id: Boolean(wx.getStorageSync('userid')) == false || wx.getStorageSync('userid') == undefined ?'': wx.getStorageSync('userid') //获取是否通过二维码进入
      }).then(res => {
        that.setData({
          stast: false
        })
        if (this.data.cartId) {
          let pages = getCurrentPages();
          let prevPage = pages[pages.length - 2];
          let shopcar = prevPage.data.shopcar;
          let cartId = JSON.parse(this.data.options.cartId);
          prevPage.data.shopcar.forEach((item, index) => {
            cartId.forEach(that => {
              if (shopcar[index].id == that) {
                shopcar.splice(index, 1)
                console.log(shopcar)
              }
            })
          })
          prevPage.setData({
            shopcar
          })
        }
        that.palyPick(res.orderid, res.ordersn)
        //缓存输入了的自提信息
        // wx.setStorage({ key: 'tiemvalue', data: that.data.tiemvalue, })   //选择自提的时间
        wx.setStorage({ key: 'inCall', data: that.data.inCall, })    //电话
        wx.setStorage({ key: 'inName', data: that.data.inName, })     //名字
      }).catch(res => {
        Toast(res.message)
        this.pageLoading = !this.pageLoading;
      })
    }
  },
  // 微信支付接口
  palyPick(id, ordersn){
    var that = this
    console.log(id)
    getPayShow({
      id:id
    }).then(res=>{
      console.log(res)
      that.setData({
        stast: true
      })
      var payInfo = res.sign
      //微信支付
      wx.requestPayment({
        'timeStamp': payInfo.timeStamp,
        'nonceStr': payInfo.nonceStr,
        'package': payInfo.package,
        'signType': 'MD5',
        'paySign': payInfo.paySign,
        'success': res => {
          console.log(res)
          wx.setStorage({key: 'toprom',data:''})
          // that.setData({
          //   toprom:''
          // })
          //type0成功1失败
          wx.redirectTo({
            url: '/pages/paymensta/paymensta?type=0',
          })
        },
        'fail': err => {
          that.setData({
            stast: true
          })
          Toast('取消支付')
          wx.redirectTo({
            url: '/pages/paymensta/paymensta?type=1',
          })
        }
      })
    })
   
  },
  // 时间变换
  onChangeTime(event) {
    const { picker, value, index } = event.detail;
    picker.setColumnValues(1, citys[value[0]]);
  },
  // 点击跳转收货地址
  onAdder() {
    wx.navigateTo({
      url: '/pages/myaddress/myaddress?stash=1',
    })
  },
  //点击跳转附近门店
  onNearby() {
    wx.navigateTo({
      url: '/pages/nearbystore/nearbystore',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorage({
      key: 'toprom',
      success: function(res) {console.log('删除成功')},
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})